'''
    请求图片地址
'''
import os
import hashlib
from utils.response import CommonResponseMixin, wrap_json_response, ReturnCode
from django.http import Http404, FileResponse, JsonResponse
from django.views import View
from backend import settings


# 图片类视图
# 类视图需要继承 Django 的 View 类
# 类同时继承 CommonResponseMixin 类
class ImaView(View, CommonResponseMixin):
    # 根据文件名获取文件
    def get(self, request):
        md5 = request.GET.get('md5')
        img_file = os.path.join(settings.IMAGES_DIR, md5 + '.jpg')
        if not os.path.exists(img_file):
            return Http404()
        else:
            return FileResponse(open(img_file, 'rb'), content_type='image/jpeg')  # content_type 表面字段是怎么样的内容

    # 上传文件
    def post(self, request):
        response = []
        files = request.FILES # 获取文件
        # key是文件名 value是文件内容
        for key, value in files.items():
            content = value.read()
            md5 = hashlib.md5(content).hexdigest() # 将内容转成16进制MD5
            path = os.path.join(settings.IMAGES_DIR, md5 + '.jpg')
            with open(path, 'wb') as f:
                f.write(content)
            response.append({
                'name': key,
                'md5': md5
            })
        message = 'post method success'
        response = self.wrap_json_response(data=response, message=message) # 通过继承 Mixin 所得
        return JsonResponse(data=response, safe=False)

    def delete(self, request):
        md5 = request.GET.get('md5') # 从请求的 Url 中取出md5
        img_name = md5 + '.jpg'
        path = os.path.join(settings.IMAGES_DIR, img_name)
        # 如果路径存在
        if os.path.exists(path):
            os.remove(path) # 删除文件
            message = 'remove success'
        else:
            message = 'file(%s) not found' % img_name
        response = self.wrap_json_response(message=message) # 通过继承 Mixin 所得
        return JsonResponse(data=response, safe=False)

    def put(self, request):
        message = 'put method success'
        response = self.wrap_json_response(message=message) # 通过继承 Mixin 所得
        return JsonResponse(data=response, safe=False)
        pass


class ImageListView(View, CommonResponseMixin):
    def get(self, request):
        response_data = []
        image_files = os.listdir(settings.IMAGES_DIR)
        for image_file in image_files:
            response_data.append({
                "name": image_file,
                "md5": image_files[:-4]
            })
        response = self.wrap_json_response(data=response_data)
        return JsonResponse(data=response)


# 返回图文消息
def image_text(request):
    if request.method == 'GET':
        md5 = request.GET.get('md5')
        imgfile = os.path.join(settings.IMAGES_DIR, md5 + '.jpg')
        if not os.path.exists(imgfile):
            return wrap_json_response(code=ReturnCode.RESOURCES_NOT_EXISTS)
        else:
            response_data = {}
            response_data['name'] = md5 + '.jpg'
            response_data['url'] = '/service/image?md5=%s' % (md5)
            response = wrap_json_response(data = response_data)
            return JsonResponse(data=response, safe=False)
    pass
